package cn.org.channl.server;

import cn.org.channl.server.handler.ServerThreadPipeline;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * netty服务端
 * 
 * @author
 *
 */
@Slf4j
public class NettyServer {
	private static final EventLoopGroup boss = new NioEventLoopGroup();
	private static final EventLoopGroup work = new NioEventLoopGroup();

	/**
	 * 服务端监听客户端
	 * 
	 * @param port
	 */
	public void init(int port) {
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(boss, work).channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new ServerThreadPipeline());

			ChannelFuture f = b.bind(port).sync();
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			log.error("",e);
		} finally {
			boss.shutdownGracefully();
			work.shutdownGracefully();
		}
	}
}
